import axios from "axios";

//创建一个axios对象出来
const request = axios.create({
  baseURL: process.env.VUE_APP_BASEURL,
  timeout: 5000
});

//request 拦截器
//可以自请求发送前对请求做一些处理
//比如统一设置token
request.interceptors.request.use(
  config => {
      config.headers['Content-Type'] = 'application/json;charset=utf-8';

      //将token携带进header头
      const user = localStorage.getItem("user");
      if (user) {
          config.headers['token'] = JSON.parse(user).token;
      }

      return config;
  },
  error => {
      return Promise.reject(error);
  }
);

//response 拦截器
//可以在接口响应后统一处理结果
request.interceptors.response.use(
  response => {
      //response.data即为后台返回的数据Result
      let res = response.data;
      //如果是字符串，则直接转换为json对象
      if (typeof res === 'string'){
          res = res ? JSON.parse(res) : res;
      }
      return res;
  },
  error => {
      console.log('err' + error) //for debug
      return Promise.reject(error)
  }
);
export default request;